import { Service } from 'egg';

import * as crypto from "crypto"

class TokenService extends Service{
    //jwt签名
    async sign_jwt(data:any,key_id) {
      const {app} =this;
      //let time=ctx.helper.getDate(10);
      let token= await app.jwt.sign(data, app.config.jwt.secret,{
        expiresIn:'10day'
      });

      app.redis.hset("token",data[key_id],token);//设置过期时间
      return token;
    }
    //jwt解密
    async decode_jwt(token:string) {
      const {app} =this;
      try {
        return await app.jwt.verify(token,app.config.jwt.secret);
      } catch (error) {
        return {};
      }
    }
    //aes加密
    async aes_encry_pto(data){
      const {app} =this;
      var algorithm = app.config.aesAlgorithm;
      var key = app.config.aesKey;
      
      var clearEncoding = app.config.aesEncode;
      var iv = app.config.aesIv;
      var cipherEncoding = app.config.aesEncoding;
      var cipher:any = crypto.createCipheriv(algorithm, key,iv);
      var cipherChunks:any = [];
      data=JSON.stringify(data);
      //console.log(data)
      cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
      cipherChunks.push(cipher.final(cipherEncoding));
      return cipherChunks.join("");
    }
    //aes解密
    /**
     * 
     * @param cipherChunks 
     *  说明：
     *   该解密过程时复制过来的，具体逻辑可参考nodejs的AES加解密接口调用过程
     *   
     */
    async aes_decry_pto(cipherChunks){
      if(cipherChunks.indexOf(" ")>-1){
        cipherChunks=cipherChunks.split(" ").join("+")
      }
      const {app} =this;
      var algorithm = app.config.aesAlgorithm;
      var key = app.config.aesKey;
      var clearEncoding = app.config.aesEncode;
      var cipherEncoding = app.config.aesEncoding;
      var iv = app.config.aesIv;
      var decipher:any = crypto.createDecipheriv(algorithm, key,iv);
      var plainChunks:any = [];
      // for (var i = 0;i < cipherChunks.length;i++) {
      // }
      plainChunks.push(decipher.update(cipherChunks, cipherEncoding, clearEncoding));
      plainChunks.push(decipher.final(clearEncoding));
      //console.log(plainChunks);
      if(plainChunks&&plainChunks.length>0){
        let len=plainChunks.length;
        let str="";
        for(let i=0;i<len;i++){
          str+=plainChunks[i];
        }
        return JSON.parse(str);
      }
      return plainChunks
    }
}

export=TokenService